package com.mygame.xinyue;

import com.mygame.common.component.Component;
import com.mygame.common.component.RouteComponent;
import com.mygame.common.component.Schedule;
import com.mygame.common.component.extend.ObjectReference;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

public class GameEngine {
    private static ObjectReference<GameEngine> ref = new ObjectReference<>();

    private Map<Class<? extends Component>, Component> componentsMap = new LinkedHashMap<>();
    private Schedule schedule;

    public static GameEngine me(){
        return ref.get();
    }

    public static GameEngine createApp(String configPath, String envName, String nodeId) throws Exception {
        GameEngine gameEngine = new GameEngine(configPath, "env", envName, nodeId);
        ref.set(gameEngine);
        gameEngine.init();
        return ref.get();
    }
    /**
     * @param configPath 配置文件根路径
     * @param envDir     基于configPath根路径的环境目录
     * @param nodeId     服务器结点id
     */
    private GameEngine(String configPath, String envDir, String envName, String nodeId) throws Exception {

    }

    private void init() throws Exception {

    }

    public GameEngine addComponent(Component component) {
        this.componentsMap.put(component.getClass(), component);
        return this;
    }

    public RouteComponent route() {
        return getComponent(RouteComponent.class);
    }

    public <T extends Component> T getComponent(Class<? extends Component> clazz) {
        Component c = this.componentsMap.get(clazz);
        if (c == null) {
            final Optional<Component> result = this.componentsMap.values()
                    .stream()
                    .filter((value) -> clazz.isInstance(value))
                    .findFirst();
            if (result.isPresent()) {
                return (T) result.get();
            }
        }
        return (T) c;
    }
}
